<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Capital;
use App\Models\MallDateFinance;
use App\Models\ProjectMall;
use App\Models\ProjectMallCapital;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Arr;

class BackMoneyCountController extends Controller
{
    public function capital(Request $request){
        $lists = Capital::query()
            ->whereNotNull("begin_date")
            ->get();
        return $this->httpSuccess($lists);
    }

    public function mainQuery($input)
    {
        $capitalId = Arr::get($input,"capitalId","");
        $pmallId = Arr::get($input,"pmallId",[]);
        $beginDate = Arr::get($input,"beginDate","");
        $endDate = Arr::get($input,"endDate","");
        $datas = [
            "counts"=>[
                "dateRange"=>[
                    $beginDate,
                    $endDate,
                ],
                "totalBackMoney"=>0,
                "avgBackMoney"=>0,
            ],
            "items"=>[],
        ];
        if(empty($capitalId)){
            $capitalId = Capital::query()
                ->whereNotNull("begin_date")
                ->pluck("id")
                ->toArray();
        }else{
            $capitalId = Capital::query()
                ->where("id",$capitalId)
                ->whereNotNull("begin_date")
                ->pluck("id")
                ->toArray();
            if(empty($capitalId)){
                return $datas;
            }
            $capitalId = [$capitalId];
        }
        if(empty($capitalId)){
            return $datas;
        }

        $pdatas = ProjectMallCapital::query()
            ->from("project_mall_capital as a")
            ->join("project_mall as b","a.p_mall_id","=","b.id")
            ->join("project as c","b.project_id","=","c.id")
            ->whereIn("a.capital_id",$capitalId)
            ->when(!empty($pmallId), function (Builder $query)use($pmallId) {
                $query->whereIn("b.id",$pmallId);
            })
            ->where("b.status",1)
            ->where("c.status",1)
            ->select("a.capital_id","b.merchant_no")
            ->get();
        $merchantNos = array_unique($pdatas->pluck("merchant_no")->toArray());
        $capitalIds = array_unique($pdatas->pluck("capital_id")->toArray());
        $mallRateDatas = ProjectMall::query()
            ->with([
                "capitalRel"
            ])
            ->whereIn("merchant_no",$merchantNos)
            ->get();
        $capitalDatas = Capital::query()
            ->whereIn("id",$capitalIds)
            ->get();
        $capitalRates = [];
        foreach ($mallRateDatas as $mallRateData){
            $totalMoney = $mallRateData->money;
            $temp = [];
            foreach ($mallRateData->capitalRel as $item){
                if(!in_array($item->capital_id,$capitalIds)) continue;
                $temp[$item->capital_id] = $item->money / $totalMoney;
            }
            $capitalRates[$mallRateData->merchant_no] = $temp;
        }
        $minDate = strtotime($capitalDatas->min("begin_date"));
        $dataMinDate = MallDateFinance::query()
            ->whereIn("merchant_no",$merchantNos)
            ->min("date");
        $minDate = strtotime($dataMinDate) >= $minDate ? strtotime($dataMinDate) : $minDate;

        $realMinDate = date("Y-m-d",$minDate);
        if(!empty($beginDate) && strtotime($beginDate) >= $minDate){
            $minDate = strtotime($beginDate);
        }
//        var_dump($merchantNos);
//        exit();
        $dataMinDate = MallDateFinance::query()
            ->whereIn("merchant_no",$merchantNos)
            ->max("date");
        $realMaxDate = $dataMinDate;
        $maxDate = !empty($endDate) && strtotime($endDate) <= strtotime($dataMinDate) ? strtotime($endDate) : strtotime($dataMinDate);
        $minDateStr = date("Y-m-d",$minDate);
        $maxDateStr = date("Y-m-d",$maxDate);
        $finances = MallDateFinance::query()
            ->whereIn("merchant_no",$merchantNos)
            ->where("date",">=",$realMinDate)
            ->where("date","<=",$realMaxDate)
            ->get();
        if(empty($finances->count())){
            return $datas;
        }
        $maxDate = strtotime($finances->max("date"));
        $diffDay = (strtotime($realMaxDate) - strtotime($realMinDate)) / 86400;
        $dateRange = [];
        for ($day=0;$day<=$diffDay;$day++){
            $dateRange[] = [
                "date"=>date("Y-m-d",strtotime($realMinDate) + 86400 * $day)
            ];
        }
//        var_dump($dateRange);
//        exit();
        foreach ($dateRange as $index=>&$date){
            $date["backMoney"] = 0;
            $date["totalBackMoney"] = 0;
            $date["avgBackMoney"] = 0;
            $financeCell = $finances->where("date",$date["date"])->collect();
            foreach ($financeCell as $cell){
                $capitalRate = $capitalRates[$cell->merchant_no];
                foreach ($capitalRate as $capitalId=>$rate){
                    $capitalCell = $capitalDatas->where("id",$capitalId)->first();
                    if(strtotime($capitalCell->begin_date) > strtotime($date["date"])) continue;
                    $date["backMoney"] += $cell->settle_money * $rate;
                }
            }
            $date["backMoney"] = round($date["backMoney"],2);
            for($i=0;$i<=$index;$i++){
                $date["totalBackMoney"] += $dateRange[$i]["backMoney"];
            }
            $date["totalBackMoney"] = round($date["totalBackMoney"],2);
            $date["avgBackMoney"] = round($date["totalBackMoney"] / ($index + 1),2);
        }
//        $datas["counts"]["totalBackMoney"] = $dateRange[count($dateRange)-1]["totalBackMoney"];
//        $datas["counts"]["avgBackMoney"] = $dateRange[count($dateRange)-1]["avgBackMoney"];
        unset($date);
        foreach ($dateRange as $index=>&$date){
            if(!empty($beginDate) and strtotime($date["date"]) < strtotime($beginDate)){
                unset($dateRange[$index]);
                unset($date);
                continue;
            }

            if(!empty($endDate) and strtotime($date["date"]) > strtotime($endDate)){
                unset($dateRange[$index]);
                unset($date);
                continue;
            }
            $datas["counts"]["totalBackMoney"] += $date["backMoney"];
            $date["backMoney"] = number_format($date["backMoney"],2,".","");
            $date["totalBackMoney"] = number_format($date["totalBackMoney"],2,".","");
            $date["avgBackMoney"] = number_format($date["avgBackMoney"],2,".","");
        }

        $dateRange = array_values($dateRange);

        $datas["counts"]["avgBackMoney"] = $datas["counts"]["totalBackMoney"] / count($dateRange);
        $datas["counts"]["totalBackMoney"] = number_format($datas["counts"]["totalBackMoney"],2,".","");
        $datas["counts"]["avgBackMoney"] = number_format($datas["counts"]["avgBackMoney"],2,".","");

        unset($date);
        $dateRange = array_values(array_reverse($dateRange));

        $datas["items"] = $dateRange;
        return $datas;



    }


    public function pageItems(Request $request)
    {
        $datas = $this->mainQuery($request->input());
        return $this->httpSuccess($datas);
    }
}
